package com.spica.spicaschool.ui.crearegroup

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.os.Parcelable
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.lifecycle.lifecycleScope
import androidx.navigation.Navigation
import coil.load
import com.kongzue.dialogx.dialogs.BottomDialog
import com.kongzue.dialogx.dialogs.PopTip
import com.kongzue.dialogx.dialogs.TipDialog
import com.kongzue.dialogx.dialogs.WaitDialog
import com.spica.spicaschool.BuildConfig
import com.spica.spicaschool.R
import com.spica.spicaschool.base.BaseFragment
import com.spica.spicaschool.databinding.FragmentCreateGroupBinding
import com.spica.spicaschool.network.Url
import com.spica.spicaschool.utils.*
import com.tencent.cos.xml.CosXmlService
import com.tencent.cos.xml.exception.CosXmlClientException
import com.tencent.cos.xml.exception.CosXmlServiceException
import com.tencent.cos.xml.listener.CosXmlResultListener
import com.tencent.cos.xml.model.CosXmlRequest
import com.tencent.cos.xml.model.CosXmlResult
import com.tencent.cos.xml.transfer.COSXMLUploadTask
import com.tencent.cos.xml.transfer.TransferConfig
import com.tencent.cos.xml.transfer.TransferManager
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import rxhttp.wrapper.param.RxHttp
import timber.log.Timber
import java.io.File
import java.util.*

/**
 * 创建组队
 */
private const val BUCKET_NAME = "spica-school-1258775535"//存储筒名称
private const val RES_IMAGE = 100

class CreateGroupFragment : BaseFragment<FragmentCreateGroupBinding>(), CosXmlResultListener {

  private var imageSelected: Uri? = null //存放选中照片的Uri

  //腾讯云对象存储服务
  private lateinit var cosXmlService: CosXmlService

  private lateinit var transferManager: TransferManager

  private var cosxmlTask: COSXMLUploadTask? = null

  private var head: String? = null

  override fun setupViewBinding(
    inflater: LayoutInflater,
    container: ViewGroup?
  ): FragmentCreateGroupBinding = FragmentCreateGroupBinding.inflate(inflater, container, false)


  override fun init() {
    initTencentCos()
    initListener()
  }


  /**
   * 初始化监听器
   */
  private fun initListener() {
    viewBinding.btnUpdateImage.setOnClickListener {
      chooseImage()
    }
    viewBinding.btnSave.setOnClickListener {
      RxHttp.postForm(Url.TEAM_ADD)
        .add(
          "token",
          SpUtils.getSpValue(
            context = requireContext(),
            key = TOKEN_SIGN,
            defaultVal = ""
          )
        )
        .add("name", viewBinding.etGroupName.text.toString())
        .add("desc", viewBinding.etGroupDesc.text.toString())
        .add("loc", viewBinding.etGroupPlace.text.toString())
        .add("headImg", head)
        .asOkResponse()
        .subscribe({
          viewBinding.root.post {
            if (it.code == 200) {
              Navigation.findNavController(
                requireActivity(),
                R.id.fragment_container_view
              ).popBackStack()

              TipDialog.setMessage("发布成功")
            } else {
              TipDialog.setMessage(it.message)
            }
          }

        }, {
          it.printStackTrace()
          BottomDialog.show("错误", it.message)
        })
    }
  }


  /**
   * 图片上传成功的回调取用
   */
  override fun onSuccess(request: CosXmlRequest?, result: CosXmlResult?) {
    lifecycleScope.launch(Dispatchers.Main) {
      Timber.e("""封面图上传成功：${result?.accessUrl.toString()}""")
      //获取最新的头像url
      head = result?.accessUrl
      //设置头像
      viewBinding.ivAvavtar.load(head) {
        placeholder(R.drawable.default_head)//占位图
        error(R.drawable.default_head) //圆形裁切
      }
      //关闭加载框
      WaitDialog.dismiss()
      //清除传输对象
      cosxmlTask = null
    }
  }

  /**
   * 图片上传失败的回调取用
   */
  override fun onFail(request: CosXmlRequest?, exception: CosXmlClientException?, serviceException: CosXmlServiceException?) {
    lifecycleScope.launch(Dispatchers.Main) {
      //关闭加载框
      WaitDialog.dismiss()
      //提示错误信息
      Timber.e("上传头像至腾讯COS失败${exception?.message}")
    }
  }


  /**
   * 处理选中图像的返回请求
   */
  private fun handleImageRequest(data: Intent?) {
    var imageUri: Uri?
    var queryImageUrl: String
    val exceptionHandler = CoroutineExceptionHandler { _, t ->
      t.printStackTrace()
      Toast.makeText(
        requireContext(),
        t.localizedMessage ?: "发生了一些不可预知的错误，请稍后重试",
        Toast.LENGTH_SHORT
      ).show()
    }

    lifecycleScope.launch(Dispatchers.Main + exceptionHandler) {
      if (data?.data != null) {
        //来自画廊的照片
        imageUri = data.data
        queryImageUrl = imageUri?.path ?: ""
        queryImageUrl =
          requireActivity().compressImageFile(queryImageUrl, false, imageUri!!)
        imageUri = Uri.fromFile(File(queryImageUrl))
        if (queryImageUrl.isNotEmpty()) {
          //url不为空
          imageSelected = imageUri
          upload()
        }
      } else {
        TipDialog.show("上传图像失败")
      }

    }
  }


  override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    when (requestCode) {
      RES_IMAGE -> {
        if (resultCode == Activity.RESULT_OK) {
          handleImageRequest(data)
        }
      }
    }
  }

  /**
   * 上传照片
   */
  private fun upload() {
    if (imageSelected == null) {
      Timber.e("imageSelected: 没有需要上传的文件")
      return
    }
    //原进程未结束？？？
    if (cosxmlTask != null) {
      PopTip.show("上传任务未完成，请稍后重试")
      return
    }
    val file = File(
      FilePathHelper.getAbsPathFromUri(
        requireContext(),
        imageSelected
      )
    )
    cosxmlTask = transferManager.upload(
      BUCKET_NAME, MD5Utils.encryptMD5File2String(file),
      file.path, null
    )
    cosxmlTask?.setCosXmlResultListener(this)
    cosxmlTask?.setCosXmlProgressListener { complete, target ->
      refreshUploadProgress(
        complete,
        target
      )
    }

  }


  /**
   * @param progress 已上传文件大小
   * @param total 文件总大小
   */
  private fun refreshUploadProgress(progress: Long, total: Long) {
    val fraction: Float = progress / total * 100.0.toFloat()
    Timber.e("上传进度：${fraction}%")
  }

  /**
   * 初始化腾讯云存储服务
   */
  private fun initTencentCos() {
    cosXmlService = CosServiceFactory.getCosXmlService(
      requireContext(),
      BuildConfig.COS_SECRET_ID,
      BuildConfig.COS_SECRET_KEY,
      true
    )
    val transferConfig = TransferConfig.Builder().build()
    transferManager = TransferManager(cosXmlService, transferConfig)
  }

  @Suppress("DEPRECATION")
  private fun chooseImage() {
    Timber.e("选择图库照片作为封面")
    startActivityForResult(getPickImageIntent(), RES_IMAGE)
  }


  /**
   * 获取启用原生 相机，相册的Intent
   */
  private fun getPickImageIntent(): Intent {
    var chooserIntent = Intent()

    var intentList: MutableList<Intent> = ArrayList()

    val pickIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)

    val takePhotoIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri())
    //获取画廊Intent
    intentList = addIntentsToList(requireContext(), intentList, pickIntent)
    //获取相机Intent
    intentList = addIntentsToList(requireContext(), intentList, takePhotoIntent)

    if (intentList.size > 0) {
      chooserIntent = Intent.createChooser(
        intentList.removeAt(intentList.size - 1),
        "选择您想插入的图片"
      )
      chooserIntent.putExtra(
        Intent.EXTRA_INITIAL_INTENTS,
        intentList.toTypedArray<Parcelable>()
      )
    }
    return chooserIntent
  }

  private fun setImageUri(): Uri {
    val imageUri: Uri
    val folder = File("${requireContext().getExternalFilesDir(Environment.DIRECTORY_DCIM)}")
    folder.mkdirs()
    val file = File(folder, "Image_Tmp.jpg")
    if (file.exists())
      file.delete()
    file.createNewFile()
    imageUri = FileProvider.getUriForFile(
      requireContext(),
      BuildConfig.APPLICATION_ID + ".fileProvider",
      file
    )
    return imageUri
  }

  @SuppressLint("QueryPermissionsNeeded")
  private fun addIntentsToList(
    context: Context,
    list: MutableList<Intent>,
    intent: Intent
  ): MutableList<Intent> {
    val resInfo = context.packageManager.queryIntentActivities(intent, 0)
    for (resolveInfo in resInfo) {
      val packageName = resolveInfo.activityInfo.packageName
      val targetedIntent = Intent(intent)
      targetedIntent.setPackage(packageName)
      list.add(targetedIntent)
    }
    return list
  }


}